import React, { useState } from 'react';
import { Form, Select, Input, Button, Space, Table, Tag, Popconfirm } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import type { FormInstance } from 'antd/es/form';

const { Option } = Select;
const { TextArea } = Input;

interface ConditionConfigStepProps {
  form: FormInstance;
}

const ConditionConfigStep: React.FC<ConditionConfigStepProps> = ({ form }) => {
  const [conditionModalVisible, setConditionModalVisible] = useState(false);
  const [editingCondition, setEditingCondition] = useState<any>(null);

  const operatorOptions = [
    { value: '=', label: '等于' },
    { value: '!=', label: '不等于' },
    { value: '>', label: '大于' },
    { value: '>=', label: '大于等于' },
    { value: '<', label: '小于' },
    { value: '<=', label: '小于等于' },
    { value: 'LIKE', label: '包含' },
    { value: 'NOT LIKE', label: '不包含' },
    { value: 'IN', label: '在列表中' },
    { value: 'NOT IN', label: '不在列表中' },
    { value: 'BETWEEN', label: '在范围内' },
  ];

  const logicOptions = [
    { value: 'AND', label: '并且' },
    { value: 'OR', label: '或者' },
  ];

  const conditions = form.getFieldValue('conditions') || [];
  const tables = form.getFieldValue('tables') || [];

  const handleAddCondition = () => {
    setEditingCondition({
      id: Date.now().toString(),
      tableName: '',
      fieldName: '',
      operator: '=',
      value: '',
      logic: 'AND',
    });
    setConditionModalVisible(true);
  };

  const handleEditCondition = (condition: any) => {
    setEditingCondition(condition);
    setConditionModalVisible(true);
  };

  const handleDeleteCondition = (conditionId: string) => {
    const currentConditions = form.getFieldValue('conditions') || [];
    const newConditions = currentConditions.filter((item: any) => item.id !== conditionId);
    form.setFieldValue('conditions', newConditions);
  };

  const handleSaveCondition = (condition: any) => {
    const currentConditions = form.getFieldValue('conditions') || [];
    if (editingCondition && editingCondition.id) {
      // 编辑现有条件
      const index = currentConditions.findIndex((item: any) => item.id === condition.id);
      if (index !== -1) {
        currentConditions[index] = condition;
      }
    } else {
      // 添加新条件
      currentConditions.push(condition);
    }
    form.setFieldValue('conditions', currentConditions);
    setConditionModalVisible(false);
    setEditingCondition(null);
  };

  const columns = [
    {
      title: '序号',
      key: 'index',
      width: 60,
      render: (_: any, __: any, index: number) => index + 1,
    },
    {
      title: '数据表',
      dataIndex: 'tableName',
      key: 'tableName',
      width: 120,
    },
    {
      title: '字段',
      dataIndex: 'fieldName',
      key: 'fieldName',
      width: 120,
    },
    {
      title: '操作符',
      dataIndex: 'operator',
      key: 'operator',
      width: 100,
      render: (operator: string) => {
        const option = operatorOptions.find(opt => opt.value === operator);
        return option ? option.label : operator;
      },
    },
    {
      title: '值',
      dataIndex: 'value',
      key: 'value',
      ellipsis: true,
    },
    {
      title: '逻辑',
      dataIndex: 'logic',
      key: 'logic',
      width: 80,
      render: (logic: string) => (
        <Tag color={logic === 'AND' ? 'blue' : 'orange'}>
          {logic === 'AND' ? '并且' : '或者'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      render: (_: any, record: any) => (
        <Space size="small">
          <Button
            type="link"
            size="small"
            onClick={() => handleEditCondition(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个条件吗？"
            onConfirm={() => handleDeleteCondition(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              danger
              size="small"
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={handleAddCondition}
        >
          添加条件
        </Button>
      </div>

      <Table
        columns={columns}
        dataSource={conditions}
        rowKey="id"
        pagination={false}
        locale={{
          emptyText: '暂无筛选条件',
        }}
      />

      {/* 条件编辑弹窗 */}
      {conditionModalVisible && (
        <div style={{
          position: 'fixed',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          backgroundColor: 'rgba(0, 0, 0, 0.5)',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          zIndex: 1000,
        }}>
          <div style={{
            backgroundColor: 'white',
            padding: 24,
            borderRadius: 8,
            width: 500,
          }}>
            <h3>{editingCondition?.id ? '编辑条件' : '添加条件'}</h3>
            <Form
              layout="vertical"
              initialValues={editingCondition}
              onFinish={handleSaveCondition}
            >
              <Form.Item
                name="tableName"
                label="数据表"
                rules={[{ required: true, message: '请选择数据表' }]}
              >
                <Select placeholder="请选择数据表">
                  {tables.map((table: string) => (
                    <Option key={table} value={table}>{table}</Option>
                  ))}
                </Select>
              </Form.Item>

              <Form.Item
                name="fieldName"
                label="字段名"
                rules={[{ required: true, message: '请输入字段名' }]}
              >
                <Input placeholder="请输入字段名" />
              </Form.Item>

              <Form.Item
                name="operator"
                label="操作符"
                rules={[{ required: true, message: '请选择操作符' }]}
              >
                <Select placeholder="请选择操作符">
                  {operatorOptions.map(option => (
                    <Option key={option.value} value={option.value}>
                      {option.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>

              <Form.Item
                name="value"
                label="值"
                rules={[{ required: true, message: '请输入值' }]}
              >
                <TextArea 
                  rows={2} 
                  placeholder="请输入值，多个值用逗号分隔"
                />
              </Form.Item>

              <Form.Item
                name="logic"
                label="逻辑关系"
                rules={[{ required: true, message: '请选择逻辑关系' }]}
              >
                <Select placeholder="请选择逻辑关系">
                  {logicOptions.map(option => (
                    <Option key={option.value} value={option.value}>
                      {option.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>

              <Form.Item>
                <Space>
                  <Button onClick={() => setConditionModalVisible(false)}>
                    取消
                  </Button>
                  <Button type="primary" htmlType="submit">
                    保存
                  </Button>
                </Space>
              </Form.Item>
            </Form>
          </div>
        </div>
      )}
    </div>
  );
};

export default ConditionConfigStep;